import Vue from "vue";

import { getTypes, publish, getLists, article } from "../../api/index";

import moment from "moment";

export default {
  state: {
    // 分类列表
    types: [],
    list: {},
    article: null
  },
  getters: {
    types(state) {
      return state.types;
    },
    list(state) {
      return state.list;
    },
    article(state) {
      return state.article;
    }
  },
  mutations: {
    setArticleState(state, { key, value }) {
      state[key] = value;
    },
    setList(state, { key, value }) {
      Vue.set(state.list, key, value);
    }
  },
  actions: {
    getTypes({ state, commit }) {
      state.types.length === 0 &&
        getTypes({
          success(res) {
            commit("setArticleState", {
              key: "types",
              value: res.typeLists
            });
          }
        });
    },
    publish(store, data) {
      return new Promise((reslove, reject) => {
        publish({
          success(res) {
            console.log(res);
            reslove();
          },
          fail() {
            reject();
          },
          data
        });
      });
    },
    getLists({ state, commit }, type) {
      return new Promise((reslove, reject) => {
        if (!state.list[type]) {
          getLists({
            success(res) {
              let value = res.articleLists.map(item => {
                item.date = moment(+item.createdAt).format("YYYY-MM-DD HH:mm");
                return item;
              });
              commit("setList", {
                key: type,
                value
              });
              reslove();
            },
            fail() {
              reject();
            },
            data: { type }
          });
        }
      });
    },
    getArticle({ commit }, id) {
      return new Promise((resolve, reject) => {
        article({
          success(res) {
            res.article.date = moment(+res.article.createdAt).format(
              "YYYY-MM-DD HH:mm"
            );
            commit("setArticleState", {
              key: "article",
              value: res.article
            });
            resolve();
          },
          fail() {
            reject();
          },
          data: { id }
        });
      });
    }
  }
};
